package group2.beans;

import group2.core.database.IJpaCtrl;
import group2.core.database.JpaCtrlFactory;
import group2.core.entities.CamelUser;
import group2.core.entities.Comment;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

/**
 * used when adding comments
 *
 * @author ludwig
 */
@ManagedBean
@ViewScoped
public class AddCommentControllerBean implements Serializable {

    @ManagedProperty(value = "#{addCommentBackingBean}")
    private AddCommentBackingBean addCommentBean;
    
    @ManagedProperty(value = "#{showPostViewBean}")
    private ShowPostViewBean showPostViewBean;
    private CamelUser user;

    public ShowPostViewBean getShowPostViewBean() {
        return showPostViewBean;
    }

    public void setShowPostViewBean(ShowPostViewBean showPostViewBean) {
        this.showPostViewBean = showPostViewBean;
    }

    public AddCommentBackingBean getAddCommentBean() {
        return addCommentBean;
    }

    public void setAddCommentBean(AddCommentBackingBean addCommentBean) {
        this.addCommentBean = addCommentBean;
    }

    public void addComment() {
        Comment c = new Comment(0, addCommentBean.comment, user, showPostViewBean.getPost());
        IJpaCtrl<Comment> commentCtrl = JpaCtrlFactory.getInstance().getCommentCtrl();
        commentCtrl.create(c);
        addCommentBean.setComment("");
    }

    /** Creates a new instance of AddCommentControllerBean */
    public AddCommentControllerBean() {

        FacesContext context = FacesContext.getCurrentInstance();
        HttpSession session =
                (HttpSession) context.getExternalContext().getSession(true);
        user = (CamelUser) session.getAttribute("username");
    }
}
